/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * server.java
 *
 * Created on Aug 11, 2013, 9:29:27 AM
 */
package cs137_chatapp;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 *
 * @author GON
 */
public class server extends javax.swing.JFrame implements ActionListener, Runnable {

    ArrayList clients = new ArrayList();
    public server() {
        initComponents();
        clientsListPanel.append("Server Online.\n");
        clientsListPanel.append("Users connected to server:");
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {//GEN-BEGIN:initComponents

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        chatPanel = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        messageArea = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        clientsListPanel = new javax.swing.JTextArea();
        sendButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        StatusText = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat Application");
        setBackground(new java.awt.Color(255, 255, 255));
        setLocationByPlatform(true);

        jPanel1.setBackground(new java.awt.Color(204, 204, 255));

        jScrollPane2.setBackground(new java.awt.Color(204, 204, 255));
        jScrollPane2.setEnabled(false);
        jScrollPane2.setFont(new java.awt.Font("Segoe UI Light", 0, 12));

        chatPanel.setFocusable(false);
        jScrollPane2.setViewportView(chatPanel);

        messageArea.setColumns(20);
        messageArea.setRows(3);
        messageArea.setText(" ");
        jScrollPane3.setViewportView(messageArea);

        jLabel1.setText("Enter your message here:");

        clientsListPanel.setBackground(new java.awt.Color(204, 204, 204));
        clientsListPanel.setColumns(15);
        clientsListPanel.setEditable(false);
        clientsListPanel.setRows(5);
        jScrollPane1.setViewportView(clientsListPanel);

        sendButton.setFont(new java.awt.Font("Segoe UI Light", 1, 12));
        sendButton.setText("Send");
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
                            .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE))
                .addContainerGap())
        );

        jButton1.setFont(new java.awt.Font("Segoe UI Light", 1, 12));
        jButton1.setText("Username");

        jPanel2.setBackground(new java.awt.Color(0, 0, 0));

        StatusText.setFont(new java.awt.Font("Segoe UI Light", 0, 12));
        StatusText.setForeground(new java.awt.Color(255, 255, 255));
        StatusText.setText("Status: Syncing Attachments");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(StatusText, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(StatusText, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }//GEN-END:initComponents

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed
        //try {
            String m = messageArea.getText();
            System.out.println(m);
            int i=0;
            for(; i<clientCount; i++){
                ((ClientThread)clients.get(i)).writeMsg(m);
            }
            /*bw.write(m);
            bw.newLine();
            bw.flush();
             * 
             */
            chatPanel.append("You: "+m+"\n");
            messageArea.setText(" ");
//        } catch (IOException ex) {
//            Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }//GEN-LAST:event_sendButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    ServerSocket server;
    Socket socket;
    BufferedReader inp;
    String name, serverName;
    private java.awt.List clientsList;
    int clientCount, ctr, type, board[], opponentID, ownID;

    public void acceptConnection(int port) throws IOException{
        Date det = new Date();
        DateFormat dateF = new SimpleDateFormat("MM/dd/yyyy");
        DateFormat timeF = new SimpleDateFormat("HH:mm:ss");
        try {
		server = new ServerSocket(port);
                chatPanel.append("Port "+port+" opened on local machine. "+dateF.format(det)+" "+timeF.format(det));
        }
        catch(IOException e) {
		System.exit(-1);
        }

        int clientCount = 0;
        clients = new ArrayList();
        /*
        try{
            socket = server.accept();
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            name = br.readLine();
            clientsListPanel.append("\n"+name);
            clientCount++;
            clients.add(new ClientThread());
        }
        catch(IOException ioe) {
            System.exit(-1);
        }
        */
            
        while(true){
            socket = server.accept();
            bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            if(clients.add(new ClientThread())){
                clientCount++;
            }
            System.out.println("clientCount: "+clientCount);
        }
        /*
        while(true){
            try {
                bw.write("\nHello Client!");bw.newLine();bw.flush();
                String msg = br.readLine();
                System.out.println(msg);
                chatPanel.append(msg+"\n");
            }
            catch(IOException ioe) {
                System.exit(-1);
            }
        }
         *
         */
    }

    public static void main(String args[]) throws IOException {
        System.out.println("Server");
        int port;
        String ip;

//        port = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Port Number: "));

        port = 12345;
        server serverapp = new server();
        serverapp.setVisible(true);
        serverapp.acceptConnection(port);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel StatusText;
    private javax.swing.JTextArea chatPanel;
    private javax.swing.JTextArea clientsListPanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea messageArea;
    private javax.swing.JButton sendButton;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent e) {
        Date det = new Date();
	DateFormat dateF = new SimpleDateFormat("MM/dd/yyyy");
	DateFormat timeF = new SimpleDateFormat("HH:mm:ss");

        if(e.getSource()==sendButton) {
            
        }
    }

    BufferedReader br;
    BufferedWriter bw;
    Socket s;

    public void run() {
        try{
            socket.setSoTimeout(5000);
	}catch(Exception e){}
	while (true){
		try{
                    chatPanel.append(br.readLine()+"\n");
		}catch (Exception h){}
	}
    }

    class ClientThread extends Thread {
		BufferedReader sInput;
		BufferedWriter sOutput;
		int id;
                String username;

                ClientThread() {
                        try
			{
                            sOutput = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                            sInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

				username = (String) sInput.readLine();
				chatPanel.append("\n"+username + " just connected.");
                                clientsListPanel.append("\n"+username);
			}
			catch (IOException e) {
				chatPanel.append("Exception creating new Input/output Streams: " + e);
				return;
			}
                        start();
        	}

        @Override
                public void run() {
                        String msg = "";
			while(true) {
				try {
					msg = sInput.readLine();
                                        System.out.println(sInput.readLine());
                                        chatPanel.append(username + ": " + msg+"\n");
				}
				catch (IOException e) {
					chatPanel.append(username + " Exception reading Streams: " + e);
					break;
				}
			}
			remove(id);
			close();
		}

		// try to close everything
		private void close() {
			// try to close the connection
			try {
				if(sOutput != null) sOutput.close();
			}
			catch(Exception e) {}
			try {
				if(sInput != null) sInput.close();
			}
			catch(Exception e) {};
			try {
				if(socket != null) socket.close();
			}
			catch (Exception e) {}
		}

		private boolean writeMsg(String msg) {
			try {
                            System.out.println("message: "+msg);
                            sOutput.write(msg);
                            sOutput.newLine();
                            sOutput.flush();
			}
			catch(IOException e) {
				System.out.println("Error sending message to " + username);
				System.out.println(e.toString());
			}
			return true;
		}
	}
}